package com.cgrs572.shortlink.project.initialize;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import static com.cgrs572.shortlink.project.common.constant.RedisKeyConstant.SHORT_LINK_STATS_STREAM_GROUP_KEY;
import static com.cgrs572.shortlink.project.common.constant.RedisKeyConstant.SHORT_LINK_STATS_STREAM_TOPIC_KEY;

/**
 * 初始化短链接监控Redis Stream消息队列的消费者组
 * 即：创建redis stream消息队列且stream的key为short-link:stats-stream，消费者组为short-link:stats-stream:only-group
 * 等同于：
 * XADD "short_link:stats-stream" * "New key" "New value"
 * xgroup create short_link:stats-stream short_link:stats-stream:only-group 0
 * 注意：项目启动后会自动执行以上两个redis命令，在redis创建stream（即short-link:stats-stream）并在stream中创建消费者组short-link:stats-stream:only-group
 */
@Component // 声明Bean，在项目启动时自动创建并放入到IOC容器中
@RequiredArgsConstructor
public class ShortLinkStatsStreamInitializeTask implements InitializingBean {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 参数为：短链接监控消息保存队列(即消息队列) Topic 缓存标识
        Boolean hasKey = stringRedisTemplate.hasKey(SHORT_LINK_STATS_STREAM_TOPIC_KEY);
        if (hasKey == null || !hasKey) {
            // 参数二：短链接监控消息保存队列(即消息队列) Group 缓存标识
            stringRedisTemplate.opsForStream().createGroup(SHORT_LINK_STATS_STREAM_TOPIC_KEY, SHORT_LINK_STATS_STREAM_GROUP_KEY);
        }
    }
}
